<template>
	<view class="goods-recommend">
		<view v-if="list.length" :data-theme="themeStyle">
			<!-- <view class="goods-recommend-title"><image :src="$util.img('/upload/uniapp/guess-like.png')"></image></view> -->
			<view class="goods-recommend-title"><image :src="$util.img('upload/uniapp/recommend.png')" mode="widthFix"></image></view>

			<view class="goods-list goods-list-3 single-column">
				<view class="goods-item" v-for="(item, index) in list" :key="index" @click="toDetail(item)">
					<view class="goods-img">
						<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"></image>
						<view class="color-base-bg goods-tag" v-if="goodsTag(item) != '' ">{{ goodsTag(item) }}</view>
					</view>
					
					<view class="info-wrap">
						<view class="name-wrap">
							<view class="goods-name">{{ item.goods_name }}</view>
							<view class="goods-label" v-if="goodsTag(item) != ''">{{ goodsTag(item) }}</view>
							<view class="goods-sale">
								<text class="color-tip">累积 {{ item.sale_num }} 份</text>
								<text class="split"></text>
								<text class="color-base-text" v-if="item.stock > 30">剩余 {{item.stock}} 份</text>
								<text class="color-base-text" v-else>仅剩 {{item.stock}} 份</text>
							</view>
						</view>
						
						<view class="">
							<view class="lineheight-clear">
								<view class="member-price-tag member-price-tag-vip-1" v-if="item.member_price && item.member_price == showPrice(item)">
									<image :src="$util.img('upload/uniapp/index/vip_1.png')" mode="widthFix"></image>
									<text>会员价</text>
								</view>
								<view class="member-price-tag member-price-tag-vip-2" v-else-if="item.promotion_type == 1">
									<image :src="$util.img('upload/uniapp/index/vip_2.png')" mode="widthFix"></image>
									<text>折扣价</text>
								</view>
								
								<view class="discount-price">
									<text class="unit font-size-tag">{{ $lang('common.currencySymbol') }}</text>
									<text class="price">{{ showPrice(item).split('.')[0] }}</text><text>.{{ showPrice(item).split('.')[1] }}</text>
								</view>
							</view>
							
							<view class="pro-info">
								<view class="delete-price color-tip">
									<block>
										<text class="unit">{{ $lang('common.currencySymbol') }}</text>{{ item.market_price > 0 ? item.market_price : item.price }}
									</block>
								</view>
							</view>
						</view>
						<view class="careBox" v-if="item.goods_spec_format">
							<button class="info-btn color-base-bg" @click.stop="getGoodsSkuDetail(item.sku_id)">选规格</button>
							<view v-if="item.num" class="tag-num">{{item.num}}</view>
						</view>
						<view class="careBox" v-if="!item.goods_spec_format">

							<button v-if="item.num <= 0 || !token" class="info-btn color-base-bg" @click.stop="cartNumChange('add', item, index)">加入购物车</button>
							<text v-if="item.num > 0" class="iconfont iconjianshao color-base-text" @click.stop="cartNumChange('minus', item, index)"></text>

							<input v-if="item.num > 0" :value="item.num" readonly disabled="disabled" unselectable="on" />
							<text v-if="item.num > 0" class="iconfont iconadd-fill color-base-text" @click.stop="cartNumChange('add', item, index)"></text>
						</view>
						
					</view>
				</view>
			</view>
		</view>
		<ns-goods-sku-category @getCartData="getCartData" ref="goodSkuNew" @refresh="refreshGoodsSkuDetail"></ns-goods-sku-category>
		
		<view class="circle-box" v-if="showLoading && load"><ns-loading></ns-loading></view>
		<ns-login ref="login"></ns-login>
	</view>
</template>

<script>
import nsGoodsSkuCategory from '@/components/ns-goods-sku/ns-goods-sku-category.vue';
import globalConfig from '@/common/js/golbalConfig.js';
import nsLoading from '@/components/ns-loading/ns-loading.vue';
// 商品推荐
export default {
	name: 'ns-goods-recommend',
	components: {
		nsLoading,
		nsGoodsSkuCategory
	},
	data() {
		return {
			list: [],
			page: 1,
			isAll: !0,
			isClick: true,
			showLoading: false,
			
			cartList: [],
			goodsSkuDetail: {},
			cartFlag: false,
			token: ''
		};
	},
	mixins: [globalConfig],
	props: {
		isLike: {
			type: Boolean,
			default: true
		},
		size: {
			type: [Number, String],
			default: 10
		},
		auto: {
			type: Boolean,
			default: true
		},
		load: {
			type: Boolean,
			default: true
		}
	},
	created() {
		this.token = uni.getStorageSync('token') ? uni.getStorageSync('token') : '';
	},
	computed: {
		tokenStore() {
			this.token = this.$store.state.tokenStore;
			return this.$store.state.tokenStore;
		}
	},
	watch: {
		tokenStore(val, old) {
			this.token = val;
		}
	},
	mounted() {
		if (this.auto) {
			this.getLikeList();
		}
	},
	methods: {
		init() {
			this.list = [];
			this.page = 1;
		},
		toDetail(e) {
			let data = {
				sku_id: e.sku_id
			};
			this.$util.redirectTo('/pages/goods/detail/detail', data);
		},
		getLikeList(size) {
			let that = this;
			if (!this.isClick) return;
			if (!this.isAll) return;
			this.isClick = false;
			if (this.page > 1) this.showLoading = true;
			return new Promise((resolve, reject) => {
				that.$api.sendRequest({
					url: '/api/goodssku/recommend',
					data: {
						page: this.page,
						page_size: this.auto ? this.size : size
					},
					success: res => {
						console.log(res,'/api/goodssku/recommend')
						this.showLoading = false;
						this.isClick = true;
						if (res.code == 0) {
							if (this.page == 1) {
								this.list = [];
							}
							this.list = this.list.concat(res.data.list);
							if (this.list.length == res.data.count) this.isAll = !1;
							this.page += 1;
							resolve(res.data.list);
							
							this.getCartData();
						}
					}
				});
			});
		},
		// 获取商品详情
		async getGoodsSkuDetail(skuId) {
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open(this.currentRoute);
				return;
			}
		
			let res = await this.$api.sendRequest({
				url: '/api/goodssku/getInfoForCategory',
				async: false,
				data: {
					sku_id: skuId,
				}
			});
			let data = res.data;
			if (data) {
				this.goodsSkuDetail = data;
		
				if (this.skuId == 0) this.skuId = this.goodsSkuDetail.sku_id;
		
				this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
		
				this.goodsSkuDetail.show_price = this.goodsSkuDetail.discount_price;
		
				// 当前商品SKU规格
				if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
		
				// 商品SKU格式
				if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
		
				this.$refs.goodSkuNew.show("join_cart", this.goodsSkuDetail, () => {
				this.getCartCount();
				});
			} else {
				this.$util.redirectTo('/pages/index/index/index', {}, 'reLaunch');
			}
		},
		//获取购物车数量
		getCartCount() {
			this.$store.dispatch('getCartNumber').then((e) => {
				console.log(e)
				this.cartCount = e;
			})
		},
		// 刷新商品sku详情数据
		refreshGoodsSkuDetail(goodsSkuDetail) {
			Object.assign(this.goodsSkuDetail, goodsSkuDetail);
		},
		getCartData() {
			if (!uni.getStorageSync('token')) {
				this.$emit('netFinish', true);
				return;
			}
		
			this.$api.sendRequest({
				url: '/api/cart/lists',
				success: res => {
					if (res.code >= 0) {
						this.cartList = res.data;
		
						for (let goods_index in this.list) {
							let goods_item = this.list[goods_index],
								sku_id = goods_item.sku_id,
								goods_id = goods_item.goods_id,
								num = 0,
								cart_id = '';
		
							for (let cart_index in this.cartList) {
								let cart_item = this.cartList[cart_index];
								if (goods_id == cart_item.goods_id && cart_item.activity_type == '') {
									num += cart_item.num;
									cart_id = cart_item.cart_id;
								}
							}
							goods_item.num = num;
							goods_item.cart_id = cart_id;
		
							if (typeof goods_item.num === 'undefined' || goods_item.num === null) {
								goods_item.num = 0;
							}
						}
						this.$forceUpdate();
						this.$emit('netFinish', true);
						this.$emit('getCartData', true);
					}
				}
			});
		},
		goodsImg(imgStr) {
			let imgs = imgStr.split(',');
			return imgs[0] ? this.$util.img(imgs[0], { size: 'mid' }) : this.$util.getDefaultImage().default_goods_img;
		},
		imgError(index) {
			this.list[index].goods_image = this.$util.getDefaultImage().default_goods_img;
		},
		showPrice(data) {
			let price = data.discount_price;
			if (data.member_price && parseFloat(data.member_price) < parseFloat(price)) price = data.member_price;
			return price;
		},
		goodsTag(data) {
			switch (data.recommend_way) {
				case 1:
					return '好货上新';
					break;
				case 2:
					return '精品优选';
					break;
				case 3:
					return '每日推荐';
					break;
				default:
					return '';
			}
		},
		
		
		// 变更购物车数量
		cartNumChange(type, goods, index) {
			if (!uni.getStorageSync('token')) {
				this.$refs.login.open('/pages/goods/cart/cart');
				return;
			}
			let cartData = {
					num: 1,
					cart_id: goods.cart_id,
					sku_id: goods.sku_id
				},
				cartUrl = "", //类型 add--新增商品  edit--修改商品数量  delete--删除商品
				actionType,
				maxBuy = goods.max_buy,
				stock = maxBuy > 0 ? (maxBuy - goods.purchased_num) : goods.stock;
		
			var minBuy = 1;
			if (goods.min_buy > 1) minBuy = goods.min_buy;
			cartData.num = minBuy; // 最少购买量
		
			goods.unit = goods.unit || "件";
		
			if (type == 'add') {
		
				// 检测是否第一次加入购物车
				if (goods.cart_id) {
					actionType = "edit";
					cartUrl = '/api/cart/edit';
				} else {
					actionType = "add";
					cartUrl = '/api/cart/add';
				}
				if (stock == 0) {
					this.$util.showToast({
						title: '库存不足'
					});
					return;
				} else if (goods.cart_id && goods.num < stock) {
					cartData.num = ++goods.num;
				} else {
					if (maxBuy > 0 && (goods.purchased_num + goods.num) >= maxBuy) {
						this.$util.showToast({
							title: '该商品每人限购' + maxBuy + goods.unit + '，您已购买了' + goods.purchased_num + goods.unit
						});
						return;
					}
		
					if (maxBuy > 0 && goods.num > 0 && goods.num + cartData.num > maxBuy) {
						var diff = maxBuy - goods.num;
						if (diff > 0) {
							this.$util.showToast({
								title: '该商品每人限购' +
									maxBuy +
									goods.unit +
									'，购物车已加入了' +
									goods.num +
									goods.unit +
									'，还能购买' +
									diff +
									goods.unit
							});
						} else {
							this.$util.showToast({
								title: '该商品每人限购' + maxBuy + goods.unit
							});
						}
						return;
					}
				}
		
			} else if (type == 'minus') {
				cartData.num = goods.num - 1 ? goods.num - 1 : 0;
				cartUrl = cartData.num > 0 ? '/api/cart/edit' : '/api/cart/delete';
				actionType = cartData.num > 0 ? 'edit' : 'delete';
			}
		
			if (this.cartFlag) return false;
			this.cartFlag = true;
		
		
			this.$api.sendRequest({
				url: cartUrl,
				data: cartData,
				success: res => {
					if (res.code >= 0) {
						if (res.data > 0) {
							this.getLikeList();
							this.shopDataChange(cartData);
							this.$emit('getCartData', true);
							this.$store.dispatch('getCartNumber');
							// this.$store.dispatch('getCartPrice');
							this.$store.dispatch('getCartIds');
							if (actionType == "edit") {
								this.cartFlag = false;
								return false;
							}
							this.list[index].cart_id = actionType == "add" ? res.data : '';
							if (actionType == 'add') {
								this.$util.showToast({
									title: '加入购物车成功'
								});
								uni.setStorageSync('isRefreshCart',1)
							}
						} else {
							cartData.num = goods.num;
							this.$util.showToast({
								title: res.message
							});
						}
					}
					this.cartFlag = false;
				}
			});
		},
		shopDataChange(data) {
			for (var i = 0; i < this.list.length; i++) {
				var item = this.list[i];
				if (data.sku_id == item.sku_id) {
					item.num = data.num;
					item.cart_id = data.cart_id;
				}
			}
			this.$forceUpdate();
		},
	}
};
</script>

<style lang="scss">
	.h40{
		height: 40rpx;
	}
	.mt-40{
		margin-top: 40rpx;
	}
.goods-recommend {
	margin-top: 74rpx;
	width: 100vw;

	.goods-recommend-title {
		text-align: center;
		margin-bottom: 30rpx;

		image {
			width: 100%;
		}
	}
}

.hr-view {
	display: flex;
	justify-content: center;
	align-items: center;
	max-width: 100%;
	box-sizing: content-box;
	font-size: $font-size-toolbar;
}

.hr-view .hr {
	width: 36%;
	height: 2rpx;
	background: #e5e5e5;
}

.hr-view .title {
	padding: 0 $padding;
}

// 商品列表双列样式
// 商品列表单列样式
.goods-list.single-column {
	
	.goods-item {
		padding: 26rpx;
		background: #fff;
		border-radius: $border-radius;
		display: flex;
		position: relative;
		margin-top: 10rpx;
		
		&.first-child {
			margin-top: 0;
		}
		
		.goods-img {
			width: 200rpx;
			height: 200rpx;
			overflow: hidden;
			border-radius: $border-radius;
			margin-right: 20rpx;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.goods-tag{
			color: #fff;
			line-height: 1;
			padding: 8rpx 12rpx;
			position: absolute;
			border-top-left-radius: $border-radius;
			border-bottom-right-radius: $border-radius;
			top: 26rpx;
			left: 26rpx;
			font-size: $font-size-goods-tag;
		}
		
		.goods-tag-img {
			position: absolute;
			border-top-left-radius: $border-radius;
			width: 80rpx;
			height: 80rpx;
			top: 26rpx;
			left: 26rpx;
			z-index: 5;
			overflow: hidden;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.info-wrap {
			flex: 1;
			display: flex;
			flex-direction: column;
		}
		
		.name-wrap {
			flex: 1;
		}
		
		.goods-name {
			font-size: $margin-both;
			height: 84rpx;
			line-height: 42rpx;
			font-weight: bold;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			position: relative;
			top: -8rpx;
		}
		
		.goods-label {
			width: 110rpx;
			height: 30rpx;
			background-color: rgba(255, 25, 25, .1);
			font-size: 22rpx;
			line-height: 30rpx;
			color: #FF4544;
			text-align: center;
			margin-bottom: 15rpx;
		}
		
		.goods-sale {
			display: flex;
			align-items: center;
			font-size: 22rpx;
			line-height: 1;
			
			.split {
				width: 1rpx;
				height: 20rpx;
				background-color: $color-tip;
				margin: 0 10rpx;
			}
		}
		
		.introduction {
			line-height: 1;
			margin-top: 10rpx;
		}
		
		.discount-price {
			display: inline-block;
			line-height: 1;
			margin-top: 16rpx;
			
			.unit {
				margin-right: 6rpx;
			}
		}
		
		.pro-info {
			display: flex;
			
			.delete-price {
				text-decoration:line-through;
				flex: 1;
				
				.unit {
					margin-right: 6rpx;
				}
			}
			
			& > view {
				line-height: 1;
				
				&:nth-child(2) {
					text-align: right;
				}
			}
		}
		
		.member-price-tag {
			display: inline-block;
			width: 60rpx;
			line-height: 1;
			margin-left: 6rpx;
			
			image {
				width: 100%;
			}
		}
		
		.member-price-tag-vip-1 {
			text {
				color: #FFFD8F;
			}
		}
	}
	
}

.goods-list-3.single-column {
	background-color: #FFFFFF;
	padding: 10rpx 30rpx 0;
	margin-bottom: 56rpx;
	
	.goods-item {
		padding: 30rpx 0;
		margin: 0;
		border-bottom: 2rpx solid #EEEEEE;
		
		&:last-child {
			border-bottom: none;
		}
		
		.name-wrap {
			flex: none;
		}
		
		.goods-img {
			width: 260rpx;
			height: 260rpx;
		}
		
		.member-price-tag {
			display: block;
			width: 93rpx;
			margin-left: 0;
			position: relative;
			margin-top: 16rpx;
			
			text {
				font-size: $font-size-tag;
				color: #FFFFFF;
				display: inline-block;
				width: 93rpx;
				height: 36rpx;
				text-align: center;
				line-height: 36rpx;
				position: absolute;
				top: 0;
				left: 0;
			}
		}
		
		.discount-price {
			margin-top: 6rpx;
			color: #FF1919;
			font-weight: bold;
			
			.price {
				font-size: 38rpx;
			}
		}
		
		.pro-info .delete-price {
			font-size: 26rpx;
		}
		
		.info-wrap {
			justify-content: space-between;
			position: relative;
		}
		
		.careBox {
			position: absolute;
			bottom: 0;
			right: 0;
			width: 182rpx;
			height: 70rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			
			.info-btn {
				width: 182rpx;
				height: 70rpx;
				margin: 0;
				color: #FFFFFF;
				line-height: 70rpx;
				padding: 0;
				font-size: 26rpx;
			}
		}
		
		.careBox input {
			font-size: 36rpx;
			font-weight: bold;
			width: 60rpx;
			padding: 0 8rpx 4rpx 4rpx;
			box-sizing: border-box;
			text-align: center;
		}
		
		.careBox .iconfont {
			font-size: 60rpx;
		}
	}
}
.tag-num-fa{
	position: relative;
}
.tag-num {
		display: block;
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		background: #FF1919;
		text-align: center;
		color: #fff;
		border-radius: 50%;
		position: absolute;
		top: -20rpx;
		right: 20rpx;
		font-size: 24rpx;
	}
	.shops-stock{
		font-size: 22rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #909399;
		padding-right: 10rpx;
	}
	.shops-sale-num{
		font-size: 22rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #FF6706;
		padding-left: 10rpx;
	}
</style>
